<?php

namespace App\Http\Services;

use App\Http\Model\Hint;
use App\Http\Model\Room;
use App\Http\Model\RoomHot;
use App\Http\Model\RoomUser;
use App\Http\Model\SuggestRoomList;
use App\Http\Model\Union;
use App\Http\Model\UnionUser;
use App\Http\Model\User;
use Carbon\Carbon;
use Illuminate\Support\Facades\Redis;

class SuggestRoomListServices extends CommonServices
{
    protected $suggestRoomListModel;//首页推荐房间列表
    protected $roomModel;//房间表
    protected $userModel;//用户
    protected $roomUserModel;//房间用户
    protected $activityService;//获取开播房间
    protected $roomHot;
    protected $model_union_user;//公会成员
    protected $model_union;//公会

    protected $popSuggestHotRoom = 'POP:SUGGEST:HOTROOM:';//string 首页推荐热一房间次数 POP:SUGGEST:HOTROOM:{USERID}:{ROOMID}=>1
    protected $popSuggestHotRoomTime = 'POP:SUGGEST:HOTROOM:TIME:';//string 2分钟限制每次弹窗 POP:SUGGEST:HOTROOM:TIME:{userId}=>time()
    protected $popSuggestHotRoomPopCount = 'POP:SUGGEST:HOTROOM:POPCOUNT:';//string 当天弹窗次数 POP:SUGGEST:HOTROOM:POPCOUNT:{$userid} => 1;
    protected $popSuggestHotRoomOpen = 'POP:SUGGEST:HOTROOM:OPEN';//string 热度推荐房间开关1=开启 0=关闭
    

    public function __construct()
    {
        $this->suggestRoomListModel = new SuggestRoomList();
        $this->roomModel = new Room();
        $this->userModel = new User();
        $this->roomUserModel = new RoomUser();
        $this->activityService = new ActivityServices();
        $this->roomHot = new RoomHot();
        $this->model_union_user = new UnionUser();
        $this->model_union = new Union();
    }
    
    //前台获取推荐房间列表
    public function getSuggestRoom(){
        $data = $this->suggestRoomListModel->getSuggestRoom();
        return $data;
    }

    //添加或更改
    public function addOrUpdate($id, $room_id, $start_time, $end_time, $sort, $is_show){
        $res = $this->suggestRoomListModel->addOrUpdate($id, $room_id, $start_time, $end_time, $sort, $is_show);
        if($res){
            return ['code'=>Hint::SUCCESS];
        }else{
            return ['code'=>Hint::ERR_DB_FAIL,'msg'=>'操作失败'];
        } 
    }

    //更改首页推荐房间状态
    public function chageStatus($param){
        $id = $param['id'];
        $showStatus = isset($param['show_status']) ? $param['show_status'] : ''; //1=显示 0=不显示
        $isDelete = isset($param['is_delete']) ? $param['is_delete'] : '';//1=删除 0=恢复
        $res = $this->suggestRoomListModel->chageStatus($id, $showStatus, $isDelete);
        if($res){
            return ['code'=>Hint::SUCCESS];
        }else{
            return ['code'=>Hint::ERR_DB_FAIL,'msg'=>'操作失败'];
        }  
    }

    //获取推荐热度房间
    public function getHotRoom($userId){
        do{
            $returnData = new \stdClass();
            //线上返空数据(安卓上线后开启)
            $openStatus = Redis::get($this->popSuggestHotRoomOpen);
            if($openStatus != 1){
                break;
            }
            //2分钟限制
            if(Redis::EXISTS($this->popSuggestHotRoomTime.$userId)){
                break;
            }
            //当天弹出次数 3次
            if(Redis::GET($this->popSuggestHotRoomPopCount.$userId) >= 3){
                break;
            }
            //判断用户是否是新用户7天内
            $userInfo = $this->userModel->get_users_by_ids([$userId]);
            $nowDate = Carbon::now()->toDateString();
            $diffDate =  Carbon::parse(date('Y-m-d H:i:s',$userInfo[0]['create_timestamp']))->toDateString();
            $compare = Carbon::parse($diffDate)->diffInDays($nowDate,true);
            //获取用户是否是主播
            $isanchor = 0;
            $res = $this->model_union_user->userToUnion($userId);
            if(!empty($res)){
                //查看公会是否认证
                $checkStatus = $this->model_union->getUnions([$res['un_id']]);
                if(isset($checkStatus[0]['authentication_status']) && $checkStatus[0]['authentication_status'] != 0){
                    $isanchor = 1;
                }
            }
            if($isanchor == 1){
                break;
            }
            if($compare > 7){
                break;
            }
            //获取在线房间
            $openList = $this->roomHot->getAllRoomHotIdData();
            
            if(empty($openList)){
                break;
            }
            $hotRoom = [];
            $openList = json_decode($openList,true);
            foreach($openList as $r){
                $userNum = $this->roomUserModel->get_users_count($r['r']);
                if(empty($userNum)) {
                    continue;
                }
                //CBD房间
                if(isset($r['b']) && $r['b'] == 1 ) {
                    $hotNum = $this->roomHot->get($r['r']);
                    $hotRoom[] = [
                        'roomId' => $r['r'],
                        'hotNum' => $hotNum
                    ];
                } 
            }
            //根据热度排序
            array_multisort(array_column($hotRoom, 'hotNum'), SORT_DESC, $hotRoom);
            //获取前五热度房间
            $hotRoom = array_slice($hotRoom,0,5);
            $hotRoomIds = array_column($hotRoom,'roomId');
            //判断今日给用户弹窗推荐热一次数
            $times = Redis::get($this->popSuggestHotRoom.$userId.':'.$hotRoomIds[0]);
            $nowTime = Carbon::now()->toDateTimeString();
            $endDayTime = Carbon::today()->endOfDay()->toDateTimeString();
            $diffTime = Carbon::parse($nowTime)->diffInSeconds($endDayTime);
            if($times >= 2){
                $room_id_key = array_rand($hotRoomIds);
                $room_id = $hotRoomIds[$room_id_key];
            }else{
                $room_id = $hotRoomIds[0];
                
                if(Redis::EXISTS($this->popSuggestHotRoom.$userId.':'.$hotRoomIds[0])){
                    Redis::INCRBY($this->popSuggestHotRoom.$userId.':'.$hotRoomIds[0],1);
                }else{
                    Redis::INCRBY($this->popSuggestHotRoom.$userId.':'.$hotRoomIds[0],1);
                    Redis::EXPIRE($this->popSuggestHotRoom.$userId.':'.$hotRoomIds[0],$diffTime);//当天结束日时间
                }
            }
            //获取房间信息
            $roomInfo = $this->roomModel->get_room($room_id);
            
            if(!empty($roomInfo)){
                //获取房间用户
                $inRoomUserId = $this->roomUserModel->get_usersids($room_id);
                if(is_array($inRoomUserId)) {
                    $inRoomUserIdSlice = array_slice($inRoomUserId, 0, 20);
                    if (count($inRoomUserIdSlice) > 0) {
                        foreach ($inRoomUserIdSlice as $uId) {
                            $roomUserInfo = $this->userModel->get_user($uId);
                            $tmpRoomUserAvatar[] = [ 'pic' => $roomUserInfo['thumbnails'], 'gender' => $roomUserInfo['gender'], 'adapt_images' => isset($roomUserInfo['images'][0]) && $roomUserInfo['images'][0] ? $roomUserInfo['images'][0].'?x-oss-process=image/resize,w_60,m_lfit' : ''];
                        }
                    }
                }
                $roomInfo['online_list'] = $tmpRoomUserAvatar;
            }
            
            $returnData = empty($roomInfo) ? [] : $roomInfo;
            //记录上一次请求时间 2分钟后缓存失效
            Redis::SET($this->popSuggestHotRoomTime.$userId,time());
            Redis::EXPIRE($this->popSuggestHotRoomTime.$userId,120);//2分钟失效
            //当天弹窗次数
            if(Redis::EXISTS($this->popSuggestHotRoomPopCount.$userId)){
                Redis::INCRBY($this->popSuggestHotRoomPopCount.$userId,1);
            }else{
                Redis::INCRBY($this->popSuggestHotRoomPopCount.$userId,1);
                Redis::EXPIRE($this->popSuggestHotRoomPopCount.$userId,$diffTime);//当天结束日时间
            }
        }while(false);
        return $returnData;
    }
}